package map;

/**
 * 基于链表实现的Map
 * @param <K>
 * @param <V>
 */
public class LinkedListMap<K,V> implements Map<K,V> {


    private class Node{
        public K key;
        public V value;

        public Node next;

        public Node(K key,V value,Node next){
            this.key = key;
            this.value = value;
            this.next = next;
        }

        public Node(K key){
            this(key,null,null);
        }

        public Node(){
            this(null,null,null);
        }

    }


    private Node dummyHead;
    private int size;

    public LinkedListMap(){
        dummyHead = new Node();
        size = 0;
    }



    @Override
    public void add(K key, V value) {
        //key不允许重复，value可以重复
        Node node = getNode(key);
        if(node == null){
            dummyHead.next = new Node(key,value,dummyHead.next);
            size++;
        }else {
            node.value = value;
        }
    }

    @Override
    public V remove(K key) {

        Node prev = dummyHead;
        while (prev.next != null){
            if(prev.next.key.equals(key)){
                //找到了这个key对应的node，跳出循环
                break;
            }
            prev = prev.next;   //prev指针下移一位
        }

        if(prev.next != null){
            Node delNode = prev.next;   //待删除节点
            prev.next = delNode.next;   //删除节点
            delNode.next = null;        //释放指针
            size--;
            return delNode.value;
        }

        return null;
    }

    @Override
    public boolean contains(K key) {
        if(getNode(key) != null){
            return true;
        }
        return false;
    }

    @Override
    public V get(K key) {
        Node node = getNode(key);
        if(node == null){
            return null;
        }
        return node.value;
    }

    @Override
    public void set(K key, V value) {
        Node node = getNode(key);
        if(node == null){
            //key不存在，报错
        }

        node.value = value;
    }

    @Override
    public int getSize() {
        return size;
    }

    @Override
    public boolean isEmpty() {
        return size==0;
    }

    private Node getNode(K key){
        //遍历链表
        Node current = dummyHead.next;
        while (current != null){
            if(current.key.equals(key)){
                    return current;
            }
            current = current.next;
        }
        return null;
    }
}
